import csv
from pathlib import Path


def write_csv(path: Path, fieldnames: list[str]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists():
        return
    with path.open("w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=fieldnames)
        w.writeheader()


def main() -> None:
    root = Path(__file__).resolve().parents[1]
    d = root / "data_external"

    # Country-year minimum template (fastest to start; weaker identification).
    write_csv(
        d / "broadband_country_year.csv",
        [
            "cntry",
            "year",
            "fixed_broadband_per100",
            "mobile_broadband_per100",
            "internet_users_pct",
            "source",
            "notes",
        ],
    )

    # Region-year template (preferred for stronger identification).
    # `region` should align to ESS `region` coding per country; in practice you'll need a mapping table.
    write_csv(
        d / "broadband_region_year.csv",
        [
            "cntry",
            "regunit",
            "region",
            "year",
            "fixed_broadband_coverage_pct",
            "mobile_coverage_pct",
            "avg_download_mbps",
            "source",
            "notes",
        ],
    )

    # Mapping helper: ESS region codes -> external region IDs (e.g., NUTS2 code).
    write_csv(
        d / "region_crosswalk.csv",
        [
            "cntry",
            "regunit",
            "ess_region_code",
            "ess_region_label",
            "external_region_id",
            "external_region_label",
            "source",
            "notes",
        ],
    )

    print("Templates ready in data_external/")


if __name__ == "__main__":
    main()

